package uk.co.cocking.getinline2.builder;

import uk.co.cocking.getinline2.exceptions.ExceptionHandler;
import uk.co.cocking.getinline2.exceptions.LoggingExceptionHandler;
import uk.co.cocking.getinline2.pipeline.GenericPipe;
import uk.co.cocking.getinline2.pipeline.NullConsumer;
import uk.co.cocking.getinline2.pipeline.Consumer;
import uk.co.cocking.getinline2.pipeline.transformers.Transformer;

@SuppressWarnings("unchecked")
public abstract class Builder<OriginalType, IncomingType, OutgoingType>  {

	private final Transformer<IncomingType, OutgoingType> transformer;
	private final Builder<OriginalType, ?, IncomingType> previousBuilder;
	private final ExceptionHandler exceptionHandler = new LoggingExceptionHandler();
	
	public final static StringConsumerBuilder<String, String, String> SCB = new StringConsumerBuilder<String, String, String>();

	public Builder(
			Transformer<IncomingType, OutgoingType> transformer,
			Builder<OriginalType, ?, IncomingType> previousBuilder) {
				this.transformer = transformer;
				this.previousBuilder = ( Builder<OriginalType, ?, IncomingType>) previousBuilder;
	}

	public Builder() {
		transformer = null;
		previousBuilder = null;
	}

	public Consumer<OriginalType> build() {
		return followedBy(new NullConsumer<OutgoingType>());
	}

	public Consumer<OriginalType> followedBy(Consumer consumer) {
		if (previousBuilder != null) {
			return previousBuilder.followedBy(new GenericPipe(transformer, consumer, exceptionHandler));
		} else {
			return consumer;
		}
	}

}
